<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert title="注意:只允许第三级分类设置相关的参数" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
        </el-col>
      </el-row>
      <!-- 级联选择框 -->
      <el-cascader
        v-model="CateValue"
        :options="cateList"
        :props="cateListProps"
        @change="CateHandleChange"
        clearable
      ></el-cascader>
      <!-- tab区域 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!-- 列表 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handerClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本框和按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button type="danger" size="mini" @click="removeRarams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 列表 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handerClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本框和按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button type="danger" size="mini" @click="removeRarams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleName"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="dialogClose"
    >
      <!-- 主内容 -->
      <el-form :model="addForm" ref="ruleForm" label-width="80px" :rules="rules">
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleName"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 主内容 -->
      <el-form :model="editForm" ref="editRuleForm" label-width="80px" :rules="editRules">
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 分类列表
      cateList: [],
      // 级联选择框的配置
      cateListProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联现在框的值
      CateValue: [],
      // tab切换选中的值
      activeName: 'many',
      //动态路由
      manyTableData: [],
      // 静态路由+
      onlyTableData: [],
      // 对话框的显示隐藏
      addDialogVisible: false,
      //对话框数据
      addForm: {
        attr_name: ''
      },
      rules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      //修改对话框的显示隐藏
      editDialogVisible: false,
      //修改对话框数据
      editForm: {
        attr_name: ''
      },
      editRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
    },
    // 级联选择框的事件
    CateHandleChange() {
      this.getParamsData()
    },
    // tab点击切换改变触发事件函数
    tabHandleClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    async getParamsData() {
      // 选中的不是三级分类
      if (this.CateValue.length !== 3) {
        this.CateValue = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return
      }
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //对话框关闭
    dialogClose() {
      this.$refs.ruleForm.resetFields()
    },
    // 添加对话框确定事件
    addParams() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    //修改对话框关闭重置事件
    editDialogClose() {
      this.$refs.editRuleForm.resetFields()
    },
    //展示修改对话框
    async showDialog(id) {
      console.log(id)
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { attr_sel: this.activeName }
      )
      if (res.meta.status !== 200) {
        return
      }
      this.editForm = res.data
      console.log(res)
      this.editDialogVisible = true
    },
    //修改对话框的确定事件
    async editParams() {
      let { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
      this.editDialogVisible = false
    },
    //删除参数
    async removeRarams(attr_id) {
      console.log(attr_id)
      let result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('取消删除')
      }
      let { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 文本框失去焦点或按下触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveAttrVal(row)
      row.inputVisible = false
    },
    //对attr_vals的数据操作，添加数据库
    async saveAttrVal(row) {
      let { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 参数有按钮转为input框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //删除tag参数事件
    handerClose(i, row) {
      console.log(i)
      row.attr_vals.splice(i, 1)
      this.saveAttrVal(row)
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.CateValue.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId() {
      if (this.CateValue.length === 3) {
        return this.CateValue[2]
      }
      return null
    },
    titleName() {
      if (this.activeName === 'many') {
        return '静态参数'
      } else {
        return '动态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
